package com.jjshop.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import com.jjshop.R;
import com.jjshop.utils.DeviceUtils;
import com.jjshop.utils.GlobalContanst;
import com.jjshop.utils.JsonUtils;
import com.jjshop.utils.LogUtil;
import com.jjshop.utils.PreUtils;
import com.jjshop.utils.StringUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by apple on 18/6/10.
 */

public class WelcomeActivity extends BaseActivity {

    public static final String[] permissions_required = new String[]{"android.permission.READ_PHONE_STATE", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE", "android.permission.ACCESS_WIFI_STATE", "android.permission.ACCESS_NETWORK_STATE"};

    @Override
    protected int setLayoutId() {
        return R.layout.activity_welcome;
    }


    @Override
    protected void initView() {
        super.initView();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Activity activity = WelcomeActivity.this;
                if (TextUtils.isEmpty(PreUtils.getString(activity,PreUtils.DEVICE,""))){

                String info = "device=#" + StringUtil.textToMD5L32(DeviceUtils.getDeviceCode(activity)) + "#Android#" + android.os.Build.VERSION.RELEASE + "#JJdance#" + StringUtil.getAppVersionName(activity) + "#" + android.os.Build.MODEL + "#null#" + DeviceUtils.getOperators(activity) +
                        "#" + DeviceUtils.getNetworkType(activity) + "#" + DeviceUtils.getesolution(activity)[0] + "#" + DeviceUtils.getesolution(activity)[1] + "#" + DeviceUtils.getWindowSize(activity)[1] + "#" + DeviceUtils.getWindowSize(activity)[0] + "#" +
                        PreUtils.getFloat(activity, "latitude", 0) + "#" + PreUtils.getFloat(activity, "lontitude", 0) + "#";
                try {
                    String device = URLDecoder.decode(info, "UTF-8");
                    PreUtils.setString(activity, "device", device + PreUtils.getString(activity, "regId", "") + "#;");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                LogUtil.e("设备信息：" + PreUtils.getString(activity, "device", ""));

//                OkHttpUtils.get()
//                        .addHeader(GlobalContanst.COOKIE, "_uauth=" + PreUtils.getString(activity, "_uauth", "") + ";" + PreUtils.getString(activity, "device", ""))
//                        .url(GlobalContanst.UPLOAD_DEVICE)
//                        .build().execute(new StringCallback() {
//                    @Override
//                    public void onError(Request request, Exception e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onResponse(String response) {
//                        LogUtil.e("MainActivity-" + response);
//                    }
//                });
            }
            }

        }).start();

    }

    @Override
    protected void initData() {
        super.initData();
        if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                ) {
//            ActivityCompat.shouldShowRequestPermissionRationale(this,PackageManager.)

            ActivityCompat.requestPermissions(this, permissions_required, 1);
        }else{
            login();
//            new android.os.Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    goMain();
//                }
//            },1000);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

//        if(BaseAD.hasPermission(this)){
        if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
                ){
//            saveImg(mImg);
            login();
        }else{
            login();
        }
    }

    private void goMain(){
        Intent intent = new Intent(this,HomeActivity.class);
        startActivity(intent);
        finish();
    }

    private void goLogin(){
        Intent intent = new Intent(this,LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }

    private void login(){
        OkHttpUtils.get().url(GlobalContanst.JJMAIL_INDEX)
                .addHeader(GlobalContanst.COOKIE,GlobalContanst.getCookies(this))
                .addHeader(GlobalContanst.User_Agent,GlobalContanst.getUserAgent(this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        finish();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ArrayList<Map<String, String>> listMapByJson = JsonUtils.getListMapByJson(response);
                        if (listMapByJson.size()>0){
                            Map<String, String> map = listMapByJson.get(0);
                            if ("400317".equals(map.get("code"))){
                                goLogin();
                            }else{
                                String data = map.get("data");
                                ArrayList<Map<String, String>> listMapByJson1 = JsonUtils.getListMapByJson(data);
                                Map<String, String> map1 = listMapByJson1.get(0);
                                String index_data = map1.get("index_data");
                                ArrayList<Map<String, String>> listMapByJson2 = JsonUtils.getListMapByJson(index_data);
                                Map<String, String> map2 = listMapByJson2.get(0);
                                String shop_info = map2.get("shop_info");
                                ArrayList<Map<String, String>> listMapByJson3 = JsonUtils.getListMapByJson(shop_info);
                                Map<String, String> map3 = listMapByJson3.get(0);
//                                "shop_info":{
//                                    "id":"537fdt",
//                                            "shopname":"99严选自营店铺",
//                                            "shopinfo":"99严选自营店铺",
//                                            "shoplogo":"https://pimgds.999d.com/uploads/yx/24/2018-06-12/5b1f6b3385588.png",
//                                            "qrcode_img":"/qrcode/shop/1.png"
//                                },
                                String shopid = map3.get("id");
                                String shopname = map3.get("shopname");
                                String shopinfo = map3.get("shopinfo");
                                String shoplogo = map3.get("shoplogo");
                                String qrcode_img = map3.get("qrcode_img");

                                PreUtils.setString(WelcomeActivity.this,PreUtils.SHOP_ID,shopid);
                                PreUtils.setString(WelcomeActivity.this,PreUtils.SHOP_NAME,shopname);
                                PreUtils.setString(WelcomeActivity.this,PreUtils.SHOP_INFO,shopinfo);
                                PreUtils.setString(WelcomeActivity.this,PreUtils.SHOP_LOGO,shoplogo);
                                PreUtils.setString(WelcomeActivity.this,PreUtils.SHOP_IMG,qrcode_img);

                                goMain();
                            }
                        }
                    }
                });
    }
}
